#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@File: bladeCaseView.py
@Author: lijk34925 
@Date: 2024/8/16 15:40
@desc: 用例上传接口
"""
import json
import os
import shutil
import threading
from datetime import datetime
from typing import List,Dict

from fastapi import Form, UploadFile, File, APIRouter
from pydantic import BaseModel

from uploadBladeCase.bladeCaseOperate import BladeCase, CaseStatus
from BladeFerm.utils.dataoperation import YamlOperation
from BladeFerm.Lib.Common import logger
from BladeFerm.utils.basic_opration import is_dir_exist, delete_file


router = APIRouter()
CaseStatusObject = CaseStatus()

static_child_dirs = ['cases', 'platform', 'standard']

case_path = './static/cases'
base_path = './static/standard'
is_dir_exist(case_path)
is_dir_exist(base_path)


@router.get("/queryProjects/")
async def query_projects():
    config_dir = "./config"
    projects = [os.path.splitext(unit)[0] for unit in os.listdir(config_dir)]
    return {"result": projects, "status": 200, "message": "获取成功！"}


@router.get("/queryConfig/")
async def query_config(project: str, method: str):
    logger.info(f"project: {project}, method: {method}")
    if project:
        filename = f'./config/{project}.yaml'
        if method == 'config':
            with open(filename, 'r', encoding='utf-8') as f:
                content = f.read()
        else:
            content = YamlOperation(filename).readYaml()
        return {'content': content, "status": 200, "message": "获取成功！"}
    else:
        return {'content': 'Error!项目名称为空！', "status": 200, "message": "获取成功！"}


@router.post("/saveConfig/")
async def save_config(addFlag: bool = Form(False),
                      project: str = Form('金融反洗钱项目'),
                      content: str = Form('')):
    filename = f'./config/{project}.yaml'
    logger.info(f'addFlag: {addFlag}, project: {project}')
    content_new = content.replace("\r\n", "\n")
    if addFlag:
        with open(filename, 'w', encoding='utf') as f:
            f.write(content_new)
        return {'result': True, "status": 200, "message": f"{project}的配置新增成功！"}
    else:
        config_dir = 'static/config'
        is_dir_exist(config_dir)
        formatted_time = datetime.now().strftime("%Y%m%d%H%M%S")
        new_filename = f'{config_dir}/{formatted_time}_{project}.yaml'
        with open(filename, 'w+', encoding='utf-8') as f:
            temp = f.read()
            with open(new_filename, 'w', encoding='utf-8') as f2:
                f2.write(temp)
            f.write(content_new)
        return {'result': True, "status": 200, "message": f"{project}的配置保存成功！\n原始配置备份成功，参考路径：{new_filename}"}


@router.get("/deleteFilename/")
async def delete_filename(filename: str = ''):
    if filename:
        result = delete_file(filename)
        return {"status": 200, "message": "删除成功！", "result": result}
    else:
        return {"status": 500, "message": "缺少入参！"}


@router.get("/queryRecord/")
async def read_local_excel(user: str = '', page: str = 'file'):
    dir_index = 0 if page == 'file' else 1
    static_dir = "./static/" + static_child_dirs[dir_index]
    dirs = os.listdir(static_dir)
    files = []
    index = 0
    for unit in dirs:
        if user and unit != user:
            continue
        child_dir = static_dir + "\\" + unit
        lines = os.listdir(child_dir)
        for line in lines:
            fp = child_dir + "\\" + line
            temp = {'id': index, 'username': unit, 'filename': line, 'url': fp}
            files.append(temp)
            index += 1
    return {"result": files, "status": 200, "message": "获取成功！"}


@router.post("/uploadExcelCase/")
async def upload_excel(
        username: str = Form(...),
        file: UploadFile = File(...),
        caseType: str = Form(...),
        project: str = Form("金融反洗钱项目")
    ):
    '''
    ## 功能：选择excel用例上传到blade平台上，并自动绑定测试脚本和数据，将其变更为可执行的自动化用例
    - param username: blade平台登录用户名
    - param password: blade平台登录密码
    - param file: Excel用例模板，必须是从blade上导入的Excel用例。模板名称请规范命名！
    - param project: blade平台上的项目名称，例如 "金融反洗钱项目"
    - return: 接口响应结果和提示信息
    '''
    current_time = datetime.now()
    formatted_time = current_time.strftime("%Y%m%d%H%M%S")
    base_dir = ".\\static\\cases\\" + username
    is_dir_exist(base_dir)
    file_path = base_dir + "\\" + formatted_time + '_' + file.filename
    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)
    logger.info(f"upload file successful! filePath: {file_path}, caseType: {caseType}")
    files = os.listdir("./config")
    config_name = f'{project}.yaml'
    if config_name in files:
        config_path = f'./config/{project}.yaml'
    else:
        config_path = f'./config/金融反洗钱项目.yaml'
    system_params = {
        'projectRootPath': file_path,
        'username': username,
        'project': project,
        'caseType': caseType,
        'configPath': config_path
    }
    BC = BladeCase(CaseStatusObject, systemParams=system_params)
    # 创建一个线程来执行函数
    t = threading.Thread(target=BC.uploadTestCaseApi)
    t.start()
    logger.info(f"开始上传自动化用例！")
    return {'result': True, 'status': 200, 'message': '开始上传自动化用例！'}


# 定义请求数据模型
class Case(BaseModel):
    username: str
    project: str
    caseType: str = '1'
    rows: str


@router.post("/uploadCase/")
async def upload_case(data: Case):
    config_path = f'./config/{data.project}.yaml'
    system_params = {
        'projectRootPath': '',
        'username': data.username,
        'project': data.project,
        'caseType': '2' if str(data.caseType) == '2' else '1',
        'configPath': config_path
    }
    case_list = json.loads(data.rows)
    BC = BladeCase(CaseStatusObject, systemParams=system_params)
    BC.set_case_list(case_list)
    progress = BC.uploadTestCaseApi(False)
    return {'result': True, 'status': 200, 'message': '开始上传自动化用例！', 'progress': progress}


@router.get("/queryUploadProgress/")
async def query_upload_progress(username: str):
    result = CaseStatusObject.get_progress(username)
    return {'result': result, "status": 200, "message": "获取上传进度成功！"}